using UnityEngine;
using UnityEngine.Android;

[RequireComponent(typeof(AudioSource))]
public class MicrophoneSpeaker : MonoBehaviour
{
    private AudioSource audioSource;
    private bool micPermissionGranted = false;

    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        RequestMicrophonePermission();
    }

    private void RequestMicrophonePermission()
    {
        if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
        {
            Permission.RequestUserPermission(Permission.Microphone);
        }
        else
        {
            micPermissionGranted = true;
            InitializeMicrophone();
        }
    }

    void OnApplicationFocus(bool hasFocus)
    {
        if (hasFocus && !micPermissionGranted)
        {
            if (Permission.HasUserAuthorizedPermission(Permission.Microphone))
            {
                micPermissionGranted = true;
                InitializeMicrophone();
            }
            else
            {
                Debug.LogError("用户未授予麦克风权限！");
            }
        }
    }

    private void InitializeMicrophone()
    {
        if (Microphone.devices.Length > 0)
        {
            string microphone = Microphone.devices[0];
            Debug.Log($"检测到麦克风设备：{microphone}");

            AudioClip clip = Microphone.Start(microphone, true, 10, 44100);
            while (!(Microphone.GetPosition(microphone) > 0)) { }

            audioSource.clip = clip;
            audioSource.loop = true;
            audioSource.Play();

            Debug.Log("麦克风录音已启动！");
        }
        else
        {
            Debug.LogError("未检测到麦克风设备！");
        }
    }

    void OnDestroy()
    {
        if (Microphone.IsRecording(null))
        {
            Microphone.End(null);
        }
    }
}
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />